﻿using System;
using Autofac;

namespace AppFx.BizTalk.Container.Loaders
{
    /// <summary>
    /// Defers container loading to a custom assembly which will trigger the loading.
    /// This approach is intended to support testing scenarios in most cases where the test developer wants explicit control of whats in the container
    /// </summary>
    public class CustomTypeContainerLoader : IContainerLoader
    {
        public void Load(ContainerBuilder containerBuilder, string loaderKey)
        {
            var typeFullName = loaderKey;

            var loaderType = Type.GetType(typeFullName);
            if (loaderType == null)
            {
                throw new ApplicationException(string.Format("Can not find custom loader - {0}", loaderKey));
            }

            if(typeof(IContainerLoader).IsAssignableFrom(loaderType) == false)
            {
                throw new ApplicationException(string.Format("Custom Container Loader - {0} - does not implement IContainerLoader", loaderKey));
            }

            var loaderInstance = Activator.CreateInstance(loaderType);
            var loader = (IContainerLoader) loaderInstance;
            loader.Load(containerBuilder, loaderKey);            
        }
    }
}
